const { exec } = require('../db/mysql')

const getList = (author, keyword) => {
  let sql = 'select * from blogs where 1=1 '
  if (author) {
    sql += `and author = ${author} `
  }
  if (keyword) {
    sql += `and title = ${keyword}`
  }
  return exec(sql)
}

const getDetail = id => {
  let sql = `select * from blogs where id=${id}`
  return exec(sql)
}

const createArticle = data => {
  let { title, content } = data
  let author = 'zhangsan'
  const createTime = Date.now()
  let sql = `insert into blogs (title,content,author,create_time) values('${title}','${content}','${author}',${createTime})`
  return exec(sql)
}

const updateArticle = (id, data) => {
  let { title, content } = data
  let sql = `update blogs set title='${title}', content='${content}' where id=${id}`
  return exec(sql)
}

const deleteArticle = (id, author) => {
  let sql = `delete from blogs where id=${id} and author=${author}`
  return exec(sql)
}

module.exports = {
  getList,
  getDetail,
  createArticle,
  updateArticle,
  deleteArticle
}
